package wqh.controller.json;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import wqh.domain.Sensor;
import wqh.pojo.MapRet;
import wqh.pojo.SensorTree;
import wqh.service.SensorService;
import wqh.service.SystemLogService;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by devts on 2016/9/26.
 */
@Controller
@CrossOrigin(origins = "*")
@RequestMapping("/xkSensor")
public class SensorJSON {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private SensorService sensorService;

    @Resource
    private SystemLogService systemLogService;

    @ResponseBody
    @RequestMapping(value = "/getAll", method = RequestMethod.GET)
    public Object getAll()
    {
//        xkLog.addLog(systemLogService,"获取所有传感器类别。",xkLog.getSensorConfigure());
        List<Sensor> sensorList = sensorService.findAllRecord();
        return MapRet.DATA(sensorList);
    }

    @ResponseBody
    @RequestMapping(value = "/getTree", method = RequestMethod.GET)
    public Object getTree() {
//        xkLog.addLog(systemLogService,"获取所有传感器类别的树状图格式。",xkLog.getSensorConfigure());
        List<Sensor> sensorList = sensorService.findAllRecord();
        List<SensorTree> sensorTreeList = new ArrayList<SensorTree>();
        for (int i = 0; i < sensorList.size(); i++)
        {
            int level = sensorList.get(i).getLevel().intValue();
            if (level == 1) {
                int level_1_ID = sensorList.get(i).getId();
                SensorTree sensorTree = new SensorTree(sensorList.get(i).getId(),
                        sensorList.get(i).getName(),
                        sensorList.get(i).getParent_id(),
                        sensorList.get(i).getLevel());
                List<SensorTree> level2 = new ArrayList<SensorTree>();
                for (int j = 0; j < sensorList.size(); j++) {
                    int parentID = sensorList.get(j).getParent_id();
                    if (level_1_ID == parentID) {
                        int level_2_ID = sensorList.get(j).getId();
                        SensorTree level2Child = new SensorTree(sensorList.get(j).getId(),
                                sensorList.get(j).getName(),
                                sensorList.get(j).getParent_id(),
                                sensorList.get(j).getLevel());
                        List<SensorTree> level3 = new ArrayList<SensorTree>();
                        for (int k = 0; k < sensorList.size(); k++) {
                            int parentID2 = sensorList.get(k).getParent_id();
                            if (level_2_ID == parentID2) {
                                SensorTree level3Child = new SensorTree(sensorList.get(k).getId(),
                                        sensorList.get(k).getName(),
                                        sensorList.get(k).getParent_id(),
                                        sensorList.get(k).getLevel());
                                level3.add(level3Child);
                            }
                        }
                        level2Child.setChildren(level3);
                        level2.add(level2Child);
                    }
                }
                sensorTree.setChildren(level2);
                sensorTreeList.add(sensorTree);
            }
        }
        return MapRet.DATA(sensorTreeList);
    }


    @ResponseBody
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public Object add(
            //HttpServletRequest httpServletRequest,
                  //    @RequestParam(value = "type",required = true) int type,
                      @RequestParam(value = "name",required = true) String name,
                      @RequestParam(value = "parent_id",required = false,defaultValue = "0") int parent_id,
                      @RequestParam(value = "level",required = true) int level
                    //  @RequestParam(value = "detail",required = false,defaultValue = "none") String detail,
                     // @RequestParam(value = "description",required = false,defaultValue = "none") String description,

    //                  @RequestParam(value = "pictureFile",required = false) MultipartFile file
    )
    {
        //图片功能暂缓
     /*   if(file == null)
        {
            return MapRet.VALUE_ERROR("pictureFile");
        }
        String localPath = "WEB-INF\\upload\\sensor_picture\\";
        String uploadPath = httpServletRequest.getServletContext().getRealPath("/") + localPath;
        File uploadDir = new File(uploadPath);
        if(!uploadDir.exists())
        {
            uploadDir.mkdirs();
        }
        String fileName = file.getOriginalFilename();
        if(fileName != null)
        {
            try{
                byte[] bytes = file.getBytes();
                fileName = System.currentTimeMillis() + fileName;
                File serverFile = new File(uploadDir.getAbsolutePath() + File.separator + fileName);
                BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
                stream.write(bytes);
                stream.close();
                localPath += serverFile.getName();
            }catch (Exception e)
            {
                e.printStackTrace();
                logger.error("图片上传错误。");
                return MapRet.FILE_UPLOAD_ERROR();
            }
        }*/
        try {
            Sensor sensor = new Sensor(name,parent_id,(byte)level);
            sensorService.insertRecordOld(sensor);
        }catch (Exception e)
        {
            e.printStackTrace();
            logger.error(e.toString());
            return MapRet.SQL_INSERT_ERROR();
        }
        return MapRet.SQL_INSERT_SUCCESS();
    }

    @ResponseBody
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    public Object update(@RequestParam(value = "id", required = true) int id,
                        // HttpServletRequest httpServletRequest,
                        // @RequestParam(value = "type",required = true) int type,
                         @RequestParam(value = "name",required = true) String name,
                         @RequestParam(value = "parent_id",required = true) int parent_id,
                         @RequestParam(value = "level",required = true) int level
                      //   @RequestParam(value = "detail",required = false,defaultValue = "none") String detail,
                       //  @RequestParam(value = "description",required = false,defaultValue = "none") String description,
                       //  @RequestParam(value = "pictureFile") MultipartFile file
    )
    {
        //图片功能暂缓
/*        if(file == null)
        {
            return MapRet.VALUE_ERROR("pictureFile");
        }
        String localPath = "WEB-INF\\upload\\sensor_picture\\";
        String uploadPath = httpServletRequest.getServletContext().getRealPath("/") + localPath;
        File uploadDir = new File(uploadPath);
        if(!uploadDir.exists())
        {
            uploadDir.mkdirs();
        }
        String fileName = file.getOriginalFilename();
        if(fileName != null)
        {
            try{
                byte[] bytes = file.getBytes();
                fileName = System.currentTimeMillis() + fileName;
                File serverFile = new File(uploadDir.getAbsolutePath() + File.separator + fileName);
                BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
                stream.write(bytes);
                stream.close();
                localPath += serverFile.getName();
            }catch (Exception e)
            {
                e.printStackTrace();
                logger.error("图片上传错误。");
                return MapRet.FILE_UPLOAD_ERROR();
            }
        }*/
        //警告，这里没有将原始图片删除，下次版本更新要添加删除原始图片功能。
        try {
            Sensor sensor = new Sensor(id,name,parent_id,(byte)level);
            sensorService.updateRecordOld(sensor);
        }catch (Exception e)
        {
            e.printStackTrace();
            logger.error(e.toString());
            return MapRet.SQL_UPDATE_ERROR();
        }
        return MapRet.SQL_UPDATE_SUCCESS();
    }

    @ResponseBody
    @RequestMapping(value = "/delete",method = RequestMethod.GET)
    public Object delete(@RequestParam(value = "id",required = true) int id)
    {
        //警告，这里没有将原始图片删除，下次版本更新要添加删除图片功能。
        try {
            sensorService.deleteRecord(id);
        }catch (Exception e)
        {
            e.printStackTrace();
            logger.error(e.toString());
            return MapRet.SQL_DELETE_ERROR();
        }
        return MapRet.SQL_DELETE_SUCCESS();
    }

    @ResponseBody
    @RequestMapping(value = "/updateName",method = RequestMethod.POST)
    public Object updateName(@RequestParam(value = "id",required = true) int id,
                             @RequestParam(value = "name",required = true) String name)
    {
        String nameOld = null;
        try {
            nameOld = sensorService.findNameByID(id);
            sensorService.updateNameById(name,id);
        }catch (Exception e)
        {
            e.printStackTrace();
            logger.error(e.toString());
            return MapRet.SQL_UPDATE_ERROR();
        }


        return MapRet.SQL_UPDATE_SUCCESS();
    }

}
